package moddbbackendrevisited.resource;

import java.sql.*;
import moddbbackendrevisited.schema.*;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import javax.ws.rs.core.Response.*;
import moddbbackendrevisited.Main;

@Path("/tables")
public class TablesResource {

  @Context
  protected UriInfo uriInfo;
  
  /*
   * List All Tables
   * http://code.google.com/p/moddb08/wiki/BackendInterfaceVersionOne#List_All_Tables
   */
	@GET
	@Produces("application/xml")
	public Tables get() throws SQLException {
    // FIXME: SERVICE UNAVAILABLE on erro
    
    // Get all available tables
    ResultSet rs = Main.dbCon.getMetaData().getTables(null, null, null, new String[] {"TABLE"});

    // Build tables schema to respond with
    Tables ts = new Tables();

    while (rs.next()) {
      ts.add(new Table(rs.getString("TABLE_NAME")));
    }

    rs.close();

		return ts;
	}
  
  /* 
   * Add a Table
   * http://code.google.com/p/moddb08/wiki/BackendInterfaceVersionOne#Add_a_Table
   */
  @POST
  @Consumes("application/xml")
  public Response put(Table table) {

    Statement stmnt;
    
    try {
      stmnt = Main.dbCon.createStatement();
    } catch (SQLException e) {
      return Response.status(Status.SERVICE_UNAVAILABLE).build();
    }

    try {
      // Create table with chosen name
      stmnt.execute("CREATE TABLE " + table.name + " (\"id;text/plain\" INTEGER PRIMARY KEY AUTOINCREMENT)");
    } catch (SQLException e) {
      return Response.status(Status.CONFLICT).build();
    }
    
    return Response.created(uriInfo.getAbsolutePath().resolve("/tables/" + table.name)).build();
  }
}
